package org.example.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.config.R;
import org.example.domain.Post;
import org.example.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("post")
public class PostController {
    @Autowired
    PostService postService;

    @RequestMapping("test")
    public String test(){
        return "test";
    }

    @PostMapping("postList")
    public R postList(Page page, @RequestBody Post post){
        PageHelper.startPage((int) page.getCurrent(), (int) page.getSize());
        List<Post> list = postService.postList(post);
        PageInfo<Post> postPageInfo = new PageInfo<>(list);
        return R.successed(postPageInfo);
    }

    @PostMapping("postAdd")
    public R postAdd(@RequestBody Post post){
        return postService.save(post);
    }

    @PostMapping("delById")
    public R delById(Integer id){
        return postService.delById(id);
    }

    @PostMapping("updateById")
    public R updateById(@RequestBody Post post){
        return postService.updateById(post);
    }

    @PostMapping("delAll")
    public R delAll(Integer[] ids){
        for (Integer id : ids) {
            postService.delById(id);
        }
        return R.successed(null);
    }
    @Autowired
    HttpServletResponse response;
    @RequestMapping("excel")
    public R excel() throws IOException {
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);

//自定义标题别名
        writer.addHeaderAlias("id", "id");
        writer.addHeaderAlias("post_name", "post_name");
        writer.addHeaderAlias("post_code", "post_code");
        writer.addHeaderAlias("sequence", "sequence");
        writer.addHeaderAlias("status", "status");
        writer.addHeaderAlias("remark", "remark");
        writer.addHeaderAlias("update_time", "update_time");

        List<Post> list = postService.list();

        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
        ServletOutputStream out=response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
        return R.successed(null);
    }

}
